package com.xmg.p2p.base.controller;

import com.xmg.p2p.base.domain.Logininfo;
import com.xmg.p2p.base.domain.RealAuth;
import com.xmg.p2p.base.domain.Userinfo;
import com.xmg.p2p.base.interceptor.RequireLogin;
import com.xmg.p2p.base.service.IRealAuthService;
import com.xmg.p2p.base.service.IUserinfoService;
import com.xmg.p2p.base.util.JSONResult;
import com.xmg.p2p.base.util.UploadUtil;
import com.xmg.p2p.base.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;

@Controller
public class RealAuthController {
    @Autowired
    private IUserinfoService userinfoService;

    @Autowired
    private IRealAuthService realAuthService;
    @Autowired
    private ServletContext servletContext;
    /**
     *
     * 用户已经认证 就跳转到结果页面
     *
     * 用户没认证:
     *      1)有关联的实名认证对象id-->审核中
     *      2)没有关联的实名认证对象id-->去添加页面
     *
     */
    @RequestMapping("realAuth")
    public String realAuth(Model model){
        Logininfo logininfo = UserContext.getLogininfo();
        Userinfo userinfo = userinfoService.findById(logininfo.getId());
        if(userinfo.getIsRealAuth()){
            RealAuth realAuth = realAuthService.findById(userinfo.getRealAuthId());
            model.addAttribute("realAuth", realAuth);
            model.addAttribute("auditing", false);
            return "realAuth_result";
        }else {
            if (userinfo.getRealAuthId() == null) {
//                model.addAttribute("logininfo", logininfo);
                return "realAuth";
            }else{
                model.addAttribute("auditing", true);
                return "realAuth_result";
            }

        }
    }
    @RequestMapping("realAuthUpload")
    @ResponseBody
    public String realAuthUpload(MultipartFile file) {
        // 先得到basepath
        String basePath = servletContext.getRealPath("/upload");
        String fileName = UploadUtil.upload(file, basePath);
        return "/upload/" + fileName;
    }

    /**
     * 申请实名认证
     */
    @RequireLogin
    @RequestMapping("realAuth_save")
    @ResponseBody
    public JSONResult realAuthSave(RealAuth realAuth) {
        realAuthService.apply(realAuth);
        return new JSONResult();
    }
}
